package com.hancai.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hancai.constant.Constants;
import com.hancai.mapper.TRecordMapper;
import com.hancai.model.TRecord;
import com.hancai.query.RecordQuery;
import com.hancai.service.RecordService;
import com.hancai.util.JWTUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author super
 */
@Service
public class RecordServiceImpl implements RecordService {

    @Resource
    private TRecordMapper tRecordMapper;

    @Override
    public PageInfo<TRecord> getRecordByPage(Integer current, RecordQuery recordQuery) {
        // 1.设置PageHelper
        PageHelper.startPage(current, Constants.PAGE_SIZE);
        // 2.查询
        List<TRecord> list = tRecordMapper.selectRecordByPage(recordQuery);
        // 3.封装分页数据到PageInfo
        PageInfo<TRecord> info = new PageInfo<>(list);
        return info;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int saveRecord(RecordQuery recordQuery) {
        TRecord tRecord = new TRecord();

        //把RecordQuery对象里面的属性数据复制到TRecord对象里面去(复制要求：两个对象的属性名相同，属性类型要相同，这样才能复制)
        BeanUtils.copyProperties(recordQuery, tRecord);
        ////创建时间
        tRecord.setCreateTime(new Date());

        //登录人的id
        Integer loginUserId = JWTUtils.parseUserFromJWT(recordQuery.getToken()).getId();
        //创建人
        tRecord.setCreateBy(loginUserId);

        return tRecordMapper.insertSelective(tRecord);
    }

    @Override
    public TRecord getRecordById(Integer id) {
        return tRecordMapper.selectDetailByPrimaryKey(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateRecord(RecordQuery recordQuery) {
        TRecord tRecord = new TRecord();

        //把RecordQuery对象里面的属性数据复制到TRecord对象里面去(复制要求：两个对象的属性名相同，属性类型要相同，这样才能复制)
        BeanUtils.copyProperties(recordQuery, tRecord);

        //编辑时间
        tRecord.setEditTime(new Date());

        //登录人的id
        Integer loginUserId = JWTUtils.parseUserFromJWT(recordQuery.getToken()).getId();
        //创建人
        tRecord.setEditBy(loginUserId);

        return tRecordMapper.updateByPrimaryKeySelective(tRecord);
    }


    @Override
    public int delRecordById(Integer id) {
        return tRecordMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int batchDelRecordIds(List<String> idList) {
        return tRecordMapper.deleteByIds(idList);
    }

}
